<template>
  <el-upload
    ref="upload"
    class="img-uploader"
    :accept="accept"
    list-type="text"
    :action="url"
    :multiple="false"
    :show-file-list="false"
    :on-remove="handleRemoveImage"
    :http-request="uploadImgHttpRequest"
    :limit="sizeLimit"
    :before-upload="beforeUpload"
  >
    <el-button type="primary" size="mini">本地上传图片</el-button>
  </el-upload>
</template>
<script>
export default {
  name: 'UploadLocalImge',
  props: {
    accept: {
      type: String,
      default: 'JPG, .PNG, .JPEG,.jpg, .png, .jpeg'
    },
    url: {
      type: String,
      default: ''
    },
    sizeLimit: {
      type: Number,
      default: 20
    }
  },
  data() {
    return {
      imgString: ''
    }
  },
  methods: {
    reset() {
      this.$refs.upload && this.$refs.upload.clearFiles()
      this.imgString = ''
    },
    // 转换base64方法时Promise对象，必须换成同步
    async uploadImgHttpRequest(file) {
      this.imgString = await this.getBase64(file.file)
      this.$emit('change', this.imgString)
      this.$emit('getFile', file.file)
      this.reset()
    },
    // 获取图片转base64，这里用的是Promise，所以调用方法时必须转换成同步（async，await）
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    handleRemoveImage() {
      this.$refs.upload && this.$refs.upload.clearFiles()
      this.imgString = ''
    },
    beforeUpload(file) {
      // 上传前校验
      var isImg = file.type.indexOf('image/') > -1
      if (!isImg) {
        this.$message.error('只能上传图片文件!')
      }
      const isLimit = file.size / 1024 / 1024 < this.sizeLimit
      if (!isLimit) {
        this.$message.error(`上传图片大小不能超过` + this.sizeLimit + `MB！`)
      }
      if (isImg && isLimit) {
        return true
        // return this.beforeUpload(file)
      } else {
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.img-uploader {
  min-width: 130px;
  height: 28px;
  overflow: hidden;
}
</style>
